package com.walking.ds;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;


/**
 * @author walking
 * 公众号：编程大道
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> dataSourceName = new ThreadLocal<>();
    private static final Map<String,String> packageDataSourceMapping = new HashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        String s = dataSourceName.get();
        dataSourceName.remove();
        return s;
    }

    protected static void setDataSourceName(String datesourceName){
        dataSourceName.set(datesourceName);
    }

    public void setPackageDataSourceMapping(Map packageDataSourceMapping) {
        DynamicDataSource.packageDataSourceMapping.putAll(packageDataSourceMapping);
    }
    protected static void usagePackageDataSource(String packageName) {
        setDataSourceName(packageDataSourceMapping.get(packageName));
    }
}
